package com.zhj.common.web.async;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * @author zhj
 */
@Configuration
public class AsyncExecutorConfig {

    @Autowired
    private AsyncExecutorConfiguration configuration;

    /**
     * 自定义线程池参数配置
     * @return
     */
    @Bean
    @Primary
    @ConditionalOnBean(annotation = EnableAsync.class)
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        // 核心线程数
        taskExecutor.setCorePoolSize(configuration.getCoreNum());
        // 最大线程数
        taskExecutor.setMaxPoolSize(configuration.getMaxNum());
        // 空闲线程的最大存活时间
        taskExecutor.setKeepAliveSeconds(configuration.getMaxTimeoutSec());
        // 是否运行核心线程数超时
        taskExecutor.setAllowCoreThreadTimeOut(configuration.getAllowCoreThreadTimeOut());
        // 设置拒绝策略
        taskExecutor.setRejectedExecutionHandler(configuration.getRejectHandler().getRejectedExecutionHandler());
        // 设置线程名称的前缀
        taskExecutor.setThreadNamePrefix(configuration.getThreadNamePrefix());
        // 设置阻塞队列的最大容量
        taskExecutor.setQueueCapacity(configuration.getQueueCapacity());
        // 设置线程工厂
        // taskExecutor.setThreadFactory();
        // 初始化线程池
        taskExecutor.initialize();
        return taskExecutor;
    }
}
